package com.grm.distributed.lock.service;

import com.grm.distributed.lock.common.Result;
import com.grm.distributed.lock.mapper.ProductMapper;
import com.grm.distributed.lock.pojo.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 乐观锁(CAS+版本号)
 */
@Slf4j
@Service
public class ProductService3 {
    @Autowired
    private ProductMapper productMapper;

    public Result sell() {
        // 1. 查库存
        List<Product> products = productMapper.queryCAS("1001");
        Product product = products.get(0);
        // 2. 判断库存是否充足
        if (product != null && product.getCount() > 0) {
            // update product set count = count - 1 ,version = version + 1 where id = #{id} and version = #{version}
           Integer flag =  productMapper.updateForCAS(1L,product.getVersion());
           if(flag == 0){
               // 如果更新失败，递归重试
               try {
                   Thread.sleep(20);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
               sell();
           }
        }
        log.info("product current count = {}", product.getCount());
        return Result.success(product.getCount());
    }
}
